from faker import Faker
from common import snowFaker as sf
import re
import pymysql

from python_faker.faker06 import getUserIdList

# 连接数据库
conn = pymysql.connect(
    host="localhost",  # MySQL 服务器地址
    user="root",  # 你的 MySQL 用户名
    password="123456",  # 你的 MySQL 密码
    database="esl",  # 数据库名称
    charset="utf8mb4"
)
cursor = conn.cursor()

fake = Faker("zh_CN")  # 生成中国地区数据


def split_address(full_address):
    """拆分简略地址（省市区）和详细地址（街道+门牌号）"""
    match = re.match(r"(.{2,3}省)?(.{2,3}市)?(.{2,3}区|县)?(.*)", full_address)
    if match:
        province, city, district, detail = match.groups()
        short_address = "".join(filter(None, [province, city, district]))  # 拼接省市区
        return short_address, detail
    return full_address, ""

# 生成虚拟地址数据
def generate_fake_address(userId):
    """生成符合 address 表结构的假数据"""
    id = sf.get_id()
    address_id = fake.uuid4().replace('-', '')  # 生成唯一 address_id
    user_id = userId  # 模拟用户 ID
    full_address = fake.address().replace("\n", " ")  # 生成完整地址并去除换行
    short_address, detail_address = split_address(full_address)
    name = fake.name()
    phone = fake.phone_number()
    gender = fake.random_element(elements=("先生", "女士"))  # 随机生成性别
    tag_id = fake.random_element(elements=("30", "28", "29"))  # 随机标签

    return (id,address_id, user_id, short_address, detail_address, name, phone, gender, tag_id)


rows = getUserIdList()
for index,row in enumerate(rows):
    # 生成并插入 5 条地址数据
    data = generate_fake_address(row[0])
    sql = """
    INSERT INTO address (id,address_id, user_id, address_abbreviation, address_details, 
                         connection_person, connection_phone, connection_gender, tag_id)
    VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)
    """
    cursor.execute(sql, data)  # 批量插入数据
    conn.commit()  # 提交事务
    print(f"成功插入第{index+1}条数据！")

# 关闭数据库连接
cursor.close()
conn.close()
